﻿using HelenServer.Grpc.Contracts;
using HelenServer.Migrator;
using HelenServer.UserCenter.Contracts;

namespace HelenServer.UserCenter.Services;

[Injection(typeof(IUCMigrateSingal))]
public class UCMigrateSingal : GrpcMethod<byte, GrpcResult<bool>>, IUCMigrateSingal
{
    private readonly IDalMigrateService _service;

    public UCMigrateSingal(IDalMigrateService service)
    {
        _service = service;
    }

    public override async Task<GrpcResult<bool>> InvokeAsync(byte request, ServerCallContext context)
    {
        MigrateProvider.ReadyToMigrate(new ZentaoDbOptions
        {
            IP = context.RequestHeaders.GetString("zt_ip")!,
            DbPort = context.RequestHeaders.GetInt32("zt_dbport")!.Value,
            DbUser = context.RequestHeaders.GetString("zt_user")!,
            DbPassword = context.RequestHeaders.GetString("zt_pwd")!,
        });

        var result = await _service.MigrateAsync(context.CancellationToken);

        await MigrateProvider.EndMigrationAsync();

        return result.ToGrpcResult(r => r);
    }
}